package com.example.sprintboot.controller;

import com.example.sprintboot.entity.UserAddress;
import com.example.sprintboot.security.UserDetailsImpl;
import com.example.sprintboot.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user/address")
public class UserAddressController {
    
    @Autowired
    private UserAddressService userAddressService;
    
    /**
     * 获取当前登录用户ID
     */
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getUserId();
        }
        return null;
    }
    
    /**
     * 获取用户的所有地址
     */
    @GetMapping
    public Map<String, Object> getUserAddresses() {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            List<UserAddress> addresses = userAddressService.getUserAddresses(userId);
            return createSuccessResponse("获取地址列表成功", addresses);
        } catch (Exception e) {
            return createErrorResponse("获取地址列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取地址详情
     */
    @GetMapping("/{addressId}")
    public Map<String, Object> getAddressById(@PathVariable Integer addressId) {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            UserAddress address = userAddressService.getAddressById(addressId, userId);
            return createSuccessResponse("获取地址详情成功", address);
        } catch (Exception e) {
            return createErrorResponse("获取地址详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加新地址
     */
    @PostMapping
    public Map<String, Object> addAddress(@RequestBody UserAddress address) {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            // 设置用户ID
            address.setUserId(userId);
            
            UserAddress newAddress = userAddressService.addAddress(address);
            return createSuccessResponse("添加地址成功", newAddress);
        } catch (Exception e) {
            return createErrorResponse("添加地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新地址
     */
    @PutMapping("/{addressId}")
    public Map<String, Object> updateAddress(@PathVariable Integer addressId, @RequestBody UserAddress address) {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            // 设置地址ID和用户ID
            address.setAddressId(addressId);
            address.setUserId(userId);
            
            UserAddress updatedAddress = userAddressService.updateAddress(address);
            return createSuccessResponse("更新地址成功", updatedAddress);
        } catch (Exception e) {
            return createErrorResponse("更新地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除地址
     */
    @DeleteMapping("/{addressId}")
    public Map<String, Object> deleteAddress(@PathVariable Integer addressId) {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            userAddressService.deleteAddress(addressId, userId);
            return createSuccessResponse("删除地址成功", null);
        } catch (Exception e) {
            return createErrorResponse("删除地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置默认地址
     */
    @PutMapping("/{addressId}/default")
    public Map<String, Object> setDefaultAddress(@PathVariable Integer addressId) {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            userAddressService.setDefaultAddress(addressId, userId);
            return createSuccessResponse("设置默认地址成功", null);
        } catch (Exception e) {
            return createErrorResponse("设置默认地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户的默认地址
     */
    @GetMapping("/default")
    public Map<String, Object> getDefaultAddress() {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            UserAddress defaultAddress = userAddressService.getDefaultAddress(userId);
            return createSuccessResponse("获取默认地址成功", defaultAddress);
        } catch (Exception e) {
            return createErrorResponse("获取默认地址失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户地址数量
     */
    @GetMapping("/count")
    public Map<String, Object> getAddressCount() {
        try {
            Integer userId = getCurrentUserId();
            if (userId == null) {
                return createErrorResponse("用户未登录");
            }
            
            int count = userAddressService.getAddressCount(userId);
            Map<String, Object> data = new HashMap<>();
            data.put("count", count);
            return createSuccessResponse("获取地址数量成功", data);
        } catch (Exception e) {
            return createErrorResponse("获取地址数量失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("data", data);
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("data", null);
        return response;
    }
} 